const http = require('http');
const querystring=require("querystring");
const fs=require("fs");
const path=require("path");

http.createServer((request, response) => {
    const { headers, method, url } = request;
    /*let body = [];*/
    response.setHeader("Access-Control-Allow-Origin", "*")
    response.setHeader("Access-Control-Expose-Headers", "Content-Type")
    if (method === "OPTIONS") {
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
        response.setHeader("Access-Control-Allow-Headers", "X-PINGOTHER, Content-Type,Authorition")
        response.setHeader("Access-Control-Max-Age", 86400)
        response.end();
    } else {
        if (method === 'GET') {
            response.setHeader("Content-Type", "text/html")
            response.end('<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8" /><title>Document</title></head><body><form action="http://localhost:9000" method="post" enctype="multipart/form-data"><input type="file" name="file" accept="image/png,image/jpg">\
           <button>提交</button></form></body></html>');
        } else if (method === "POST") {
            var body='';
            //保存文件名
            var filename='';
            request.setEncoding('binary');
            request.on('error', (err) => {
                console.error(err);
            }).on('data', (chunk) => {
                body+=chunk;
            }).on('end', () => {
                var file=querystring.parse(body,'\r\n',":");
                var type=file["Content-Type"];
                  var boundary=/boundary=([-\w]+)/.exec(request.headers['content-type'])[1];
                  var b=body.toString();
                  var info=file['Content-Disposition'];
                  filename=/filename="([\w]+\.[\w]+)/.exec(info)[1];
                  console.log(filename+'');
                  var firstStep=b.substr(b.indexOf(type)+type.length);
                  var secondStep=firstStep.replace(/^\s\s*/,"").replace(/\s\s*$/,"");
                  var lastQuery='--'+boundary+'--';
                  var thirdStep=secondStep.substr(0,secondStep.indexOf(lastQuery));
                  fs.writeFile(filename,thirdStep,'binary',(err)=>{
                  })

                response.end("12312");
        })
    }
  }
}).listen(9000);
